package at.kokoni.Koko_Ni.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.List;

public class RestUtil {
	private HttpClient client;
	private URL url;

	public RestUtil(URL url) {
		this.client = new DefaultHttpClient();
		this.url = url;
	}

	public String get() {
		StringBuilder builder = new StringBuilder();
		try {
			HttpGet get = new HttpGet(url.toURI());
			HttpResponse response = this.client.execute(get);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream inputStream = entity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
				inputStream.close();
			} else {
				return "" + statusCode;
			}
		} catch (Exception e) {
			return null;
		}
		return builder.toString();
	}

	public String post(List<NameValuePair> nameValuePairs) {

		try {
			HttpPost httpPost = new HttpPost(url.toURI());
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));

			StringBuilder builder = new StringBuilder();
			HttpResponse response = this.client.execute(httpPost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == 200) {
				HttpEntity entity = response.getEntity();
				InputStream inputStream = entity.getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
				inputStream.close();
			} else {
				return "" + statusCode;
			}
			return builder.toString();
		} catch (Exception e) {
			return null;
		}
	}
}
